/**
 * Created by cchen on 2015/5/14.
 */
'use strict';
angular.module('backofficeApp.communityRewardRule.controller', []).
    controller('communityRewardRuleCtrl', ['$scope', 'communityRewardRuleService', function ($scope, communityRewardRuleService) {
        $scope.$watch('$viewContentLoaded', function () {
            $scope.rule_list = []
            $scope.filter="all";
            btnCtrl(false, false, false);
            listRewardRules({filter:'all'});
            $scope.reward_sources=[
                {name:'v认证',value:1},{name:'推荐用户',value:2}
            ]

            $scope.dateFrom= datePicker('#startDate');
            $scope.dateTo=   datePicker('#endDate');


            function btnCtrl(isAdd, isUpdate, isDelete) {
                $scope.addBtnShow = isAdd;
                $scope.updateBtnShow = isUpdate;
                $scope.deleteBtnShow = isDelete;
            }

            function communityModel(isShow) {
                if (isShow) {
                    $('#community_model').modal('show');
                }
                else {
                    $('#community_model').modal('hide');
                }
            }

            function initDialog(data, showDialog, btnFlag) {
                var f = [[true, false, false], [false, true, false], [false, false, true]]
                btnCtrl(f[btnFlag][0], f[btnFlag][1], f[btnFlag][2]);
                communityModel(showDialog);
                $scope.crule = data;
                $scope.onErrorMsg=""
                $scope.showErrorMsg=false;
            }


            function datePicker(id){
                function d(id){
                    var self=this;
                    $(id).datepicker({
                        format: 'yyyy-mm-dd',
                        autoclose:true,
                        forceParse:false
                    }).on('changeDate',function(e){
                        self.date= e.date;
                    }).on('show',function(e){
                        $(".datepicker.datepicker-dropdown.dropdown-menu").css("z-index","10000");

                    });

                }
                d.prototype.getValue=function(isFrom){
                    if(isFrom)
                    {
                        return this.date.setHours(0,0,0,0)
                    }
                    return this.date.setHours(23,59,59,0)
                }
                var date=new d(id);
                return date;
            }


            $scope.onErrorMsg=""
            $scope.showErrorMsg=false;

            function notValidateDate(valueA, valueB)
            {
                if(!valueA||!valueB){
                    return true
                }
                if(valueA >=valueB){
                    return true;
                }
                else{
                    return false;
                }
            }

            function validateRule(rule){
                if(!rule.community_id)
                {
                    $scope.onErrorMsg="小区选择错误"
                    $scope.showErrorMsg=true;
                    return false;

                }else if(!rule.reward_expiredate_length&&$scope.is_voucher_type===1){
                    $scope.onErrorMsg="有效期错误"
                    $scope.showErrorMsg=true;
                    return false;
                }
                else if(!rule.reward_source){
                    $scope.onErrorMsg="奖励选择错误"
                    $scope.showErrorMsg=true;
                    return false;
                }
                else if(!rule.voucher_type_id){
                    $scope.onErrorMsg="奖励类型错误"
                    $scope.showErrorMsg=true;
                    return false;
                }else if(notValidateDate(rule.from_time, rule.to_time)){
                    rule.from_time=new Date(rule.from_time).Format('yyyy-MM-dd');
                    rule.to_time=new Date(rule.to_time).Format('yyyy-MM-dd');
                    $scope.onErrorMsg="活动开始或结束日期选择错误"
                    $scope.showErrorMsg=true;
                    return false;
                }
                return true;
            }

            function listRewardRules(filter){
                communityRewardRuleService.list.get(filter,function(res){
                    $scope.rule_list=res.data;
                    $scope.filter=filter.filter;
                })
            }

            communityRewardRuleService.commList.get(function(res){
                $scope.commList=res.data;
            });
            communityRewardRuleService.typeList.get(function(res){
                $scope.typeList=res.data;
            });

            $scope.changeVoucherType=function(type_id){
                $scope.typeList.forEach(function(item){
                   if(item.id+""===type_id){
                       $scope.is_voucher_type=item.type
                   }
                })
            }

            $scope.setCommunityName=function(){
                var communityName=$("#community_menu").find("option:selected").html();
                $scope.crule.community_name=communityName;

            }

            $scope.newDialog = function () {
                initDialog({}, true, 0)
                $scope.is_voucher_type=1
            }

            $scope.updateDialog = function (rule) {
                $scope.dateFrom= datePicker('#startDate');
                $scope.dateTo=   datePicker('#endDate');
                $scope.changeVoucherType(rule.voucher_type_id);
                initDialog(rule, true, 1)
            }

            $scope.deleteDialog = function (rule) {
                $scope.changeVoucherType(rule.voucher_type_id);
                initDialog(rule, true, 2)
            }

            $scope.findCommunities = function (communityName) {

                if(communityName&&communityName.length===0)
                {
                    listRewardRules({filter:'all'});
                }else {

                    listRewardRules({filter: communityName});
                }
            }

            $scope.add = function (rule) {
                rule.from_time=$scope.dateFrom.getValue(true);
                rule.to_time=$scope.dateTo.getValue(false);
                rule.communityName=$scope.communityName?$scope.communityName:rule.communityName;
                if(!validateRule(rule))
                {
                    return;
                }
                communityRewardRuleService.obj.save(rule, function (res, arg1, arg2) {
                    listRewardRules({filter: $scope.filter});
                });
                communityModel(false)

            }

            $scope.update = function (rule) {
                var startDate=$('#startDate').val();
                var endDate=$('#endDate').val();
                var start = new Date(Date.parse(startDate));
                var end= new Date(Date.parse(endDate));
                start.setHours(0,0,0,0);
                end.setHours(23,59,59,0);
                rule.from_time=start.getTime();
                rule.to_time=end.getTime();
                if(!validateRule(rule))
                {
                    return;
                }
                communityRewardRuleService.obj.update(rule, function (res, arg1, arg2) {
                    listRewardRules({filter: $scope.filter});
                });
                communityModel(false);

            }
            $scope.delete = function (rule) {
                if(!validateRule(rule))
                {
                    return;
                }
                communityRewardRuleService.obj.delete(rule, function (res, arg1, arg2) {
                    listRewardRules({filter: $scope.filter});
                });
                communityModel(false);
            }

        });
    }])


angular.module('backofficeApp.communityRewardRule.services', ['ngResource']).
    factory('communityRewardRuleService', function ($resource) {
        return {
            obj: $resource('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/rewardRule', {}, {
                'update': {method: 'PUT'},
                'delete': {method:'DELETE'}
            }),
            list: $resource('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/rewardRule/list/:filter', {}, {}),
            commList:$resource('http://' + backOfficeHost + '/rest/v1.0/communities/getAllCommunity',{},{}),
            typeList:$resource('http://' + backOfficeHost + '/rest/v1.0/backoffice/voucher/rewardRule/type/list',{},{})
        }
    })




Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}